package com.hzncc.scaffold.controller.Rear.teachingClassroom;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Bo.ExamineeBo;
import com.hzncc.scaffold.entity.Other.*;
import com.hzncc.scaffold.entity.Vo.*;
import com.hzncc.scaffold.mapper.CourseMapper;
import com.hzncc.scaffold.mapper.UserMapper;
import com.hzncc.scaffold.service.*;
import com.hzncc.scaffold.utils.FileUtil;
import com.hzncc.scaffold.utils.NumberUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.client.utils.DateUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: DrunkBear
 * @Date: 2022-05-09 15:31
 * @Description: 课程管理
 */
@RestController
@RequestMapping("/manage/course")
@Api(tags = "教学课堂管理-课程管理")
public class CourseManageController {

    @Autowired
    CourseService courseService;

    @Autowired
    CoursemajorService coursemajorService;

    @Autowired
    MajorService majorService;

    @Autowired
    UserService userService;

    @Autowired
    ChapterService chapterService;

    @Autowired
    TaskService taskService;

    @Autowired
    CourseMapper courseMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    SqlSessionTemplate sqlSessionTemplate;

    @Value("${project.imgFileSuffix}")
    public String imgFileSuffix;

    @GetMapping("/list")
    @ApiOperation("课程管理列表")
    public ResultT list(Integer pageNum, Integer page, Integer pageSize, String keyword, Integer majorId) {
        Integer pageData = NumberUtils.pageNum(page, pageNum);
        ArrayList<CourseListVo> courseListVos = new ArrayList<>();

        QueryWrapper<Course> qw = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(keyword)) {
            qw.like("`course`.title", keyword);
        }
        if (majorId != null) {
            qw.eq("`majors`.`id`", majorId);
        }
        qw.eq("course.isDelete", 0);
//        if (pageData != null && pageSize != null && pageData > 0 && pageSize > 0) {
//            PageHelper.startPage(pageData, pageSize);
//        }
        List<Course> collect1 = courseMapper.listVo(qw);
        List<Course> courseList = collect1.stream().filter(c -> c.getMajorsPid() != null && c.getMajorsPid() != 0).collect(Collectors.toList());
        // 3. 这一步的作用主要是为了获取分页信息
        PageInfo courseListPageInfo = new PageInfo<>(courseList);
        for (Course course : courseList) {
            if (CollUtil.isNotEmpty(courseListVos)) {
                List<CourseListVo> collect = courseListVos.stream().filter(item -> item.getId().equals(course.getId())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(collect)) {
                    continue;
                }
            }
            CourseListVo courseListVo = BeanUtil.toBean(course, CourseListVo.class);
            ArrayList<Major> majorList = new ArrayList<>();
            ArrayList<Integer> idList = new ArrayList<>();
            Publisher publisher = new Publisher();

            LambdaQueryWrapper<Coursemajor> lqww = new LambdaQueryWrapper<>();
            lqww.eq(Coursemajor::getCourseId, course.getId());
            List<Coursemajor> majorIdList = coursemajorService.list(lqww);
            if (CollUtil.isNotEmpty(majorIdList)) {
                for (Coursemajor coursemajor : majorIdList) {
                    if (majorService.getById(coursemajor.getMajorId()) != null) {
                        Major major = majorService.getById(coursemajor.getMajorId());
                        idList.add(coursemajor.getMajorId());
                        majorList.add(major);
                    }
                }
            }
            if (userService.getById(course.getPublisherId()) != null) {
                User user = userService.getById(course.getPublisherId());
                publisher = BeanUtil.toBean(user, Publisher.class);
            }

            courseListVo.setPublisher(publisher);
            courseListVo.setMajors(majorList);
            courseListVos.add(courseListVo);
        }

        courseListPageInfo.setList(courseListVos);

        HashMap<String,Object> map = new HashMap<>();
        map.put("rows",courseListVos);
        map.put("count",new PageInfo<>(courseList).getTotal());
        return ResultT.success(map);

//        courseListPageInfo.setList(courseListVos);

//        List<Integer> courseIdList = courseListVos.stream().map(CourseListVo::getId).collect(Collectors.toList());
//        QueryWrapper<Course> qww = new QueryWrapper<>();
//        qww.eq("`course`.`isDelete`", 0);
//        if (majorId != null) {
//            qww.eq("majors.id", majorId);
//        }
//        if (StrUtil.isNotEmpty(keyword)) {
//            qww.like("course.title", keyword);
//        }
//        Integer total = courseMapper.selectTotal(qww);


//        return ResultT.success(courseListPageInfo);


    }

    @PostMapping("/update")
    @ApiOperation("修改课程")
    public ResultT update(@RequestBody UpdateCourseVo updateCourseVo) {
        if (courseService.getById(updateCourseVo.getCourseId()) == null) {
            return ResultT.fail("数据错误");
        }
        Course course = BeanUtil.toBean(updateCourseVo, Course.class);
        course.setId(updateCourseVo.getCourseId());

        if (updateCourseVo.getMajor() != null) {

            LambdaQueryWrapper<Coursemajor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Coursemajor::getCourseId, updateCourseVo.getCourseId());
            coursemajorService.remove(lqw);

            Coursemajor coursemajor = new Coursemajor();
            coursemajor.setCourseId(updateCourseVo.getCourseId());
            coursemajor.setMajorId(updateCourseVo.getMajor());
            coursemajorService.save(coursemajor);
        }

        if (updateCourseVo.getModule() != null) {
            Coursemajor coursemajor = new Coursemajor();
            coursemajor.setCourseId(updateCourseVo.getCourseId());
            coursemajor.setMajorId(updateCourseVo.getModule());
            coursemajorService.save(coursemajor);
        }
        if(null != course.getCover()){
            course.setCover(FileUtil.urlLastName(course.getCover()));
        }
        if("1".equals(updateCourseVo.getStatus())){
            course.setPubTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        }

        boolean update = courseService.updateById(course);
        if (update) {
            return ResultT.success();
        } else {
            return ResultT.fail("修改失败");
        }
    }

    @PostMapping("/delete")
    @ApiOperation("删除课程")
    public ResultT delete(@RequestBody CourseIdVo courseIdVo) {

        Integer courseId = courseIdVo.getCourseId();

        if (courseId == null) {
            return ResultT.fail("数据错误");
        }
        ResultT resultT = courseService.deleteCourse(courseId);
        LambdaQueryWrapper<Coursemajor> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Coursemajor::getCourseId, courseId);
        coursemajorService.remove(lqw);

        return resultT;
    }

    @PostMapping("/publish")
    @ApiOperation("发布课程管理")
    public ResultT publish(@RequestBody CourseIdVo courseIdVo) {

        Integer courseId = courseIdVo.getCourseId();

        if (courseService.getById(courseId) == null) {
            return ResultT.fail("数据错误");
        }
        Boolean update = false;
        Course course = courseService.getById(courseId);
        if (course.getStatus() == 0) {
            course.setStatus(1);
            course.setPubTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            update = courseService.updateById(course);
            if (update) {

//                //发布成功 存入课程发布成功通知
//
//                List<Integer> userIdList = userMapper.getUserId();
//
//                SqlSession session = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
//                MessageMapper mapper = session.getMapper(MessageMapper.class);
//
//                try {
//                    Message message = new Message();
//                    message.setStatus(0);
//                    message.setCreateTime(DateUtil.now());
//                    message.setContent("上新啦！" + course.getTeacher() + "老师邀您一起来学习" + "《" + course.getTitle() + "》!");
//
//                    for (Integer userId : userIdList) {
//                        message.setUserId(userId);
//                        mapper.insert(message);
//                    }
//
//                    session.commit();
//                    session.clearCache();
//
//                } catch (Exception exception) {
//                    exception.printStackTrace();
//                    session.rollback();
//                } finally {
//                    session.close();
//                }


                return ResultT.success("操作成功");
            } else {
                return ResultT.fail("操作失败");
            }
        }

        if (course.getStatus() == 1) {
            course.setStatus(0);
            update = courseService.updateById(course);
            if (update) {
                return ResultT.success("操作成功");
            } else {
                return ResultT.fail("操作失败");
            }
        }

        return ResultT.fail("操作失败");

    }

    @GetMapping("/detail")
    @ApiOperation("课程管理详细信息")
    public ResultT detail(Integer courseId) {

//        Integer courseId = courseIdVo.getCourseId();

        if (courseService.getById(courseId) == null) {
            return ResultT.fail("数据错误");
        }
        if (courseService.getById(courseId).getIsDelete() == 1) {
            return ResultT.fail("数据错误");
        }
        CourseDetailVo courseDetailVo = new CourseDetailVo();
        Course course = courseService.getById(courseId);
        courseDetailVo = BeanUtil.toBean(course, CourseDetailVo.class);

        ArrayList<ChaptersVo> chaptersVos = new ArrayList<>();

        LambdaQueryWrapper<Chapter> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Chapter::getCourseId, course.getId());
        List<Chapter> chapterList = chapterService.list(lqw);
        if (CollUtil.isNotEmpty(chapterList)) {
            for (Chapter chapter : chapterList) {
                ChaptersVo chaptersVo = BeanUtil.toBean(chapter, ChaptersVo.class);

                LambdaQueryWrapper<Task> lqww = new LambdaQueryWrapper<>();
                lqww.eq(Task::getChapterId, chapter.getId());
                List<Task> taskList = taskService.list(lqww);
                chaptersVo.setTasks(taskList);
                chaptersVos.add(chaptersVo);
            }
        }
        ArrayList<Major> majors = new ArrayList<>();

        LambdaQueryWrapper<Coursemajor> lqwww = new LambdaQueryWrapper<>();
        lqwww.eq(Coursemajor::getCourseId, course.getId());
        List<Coursemajor> coursemajorList = coursemajorService.list(lqwww);

        for (Coursemajor coursemajor : coursemajorList) {
            if (majorService.getById(coursemajor.getMajorId()) != null) {
                Major major = majorService.getById(coursemajor.getMajorId());
                majors.add(major);
            }
        }

       if(courseDetailVo.getCover() != null){
           courseDetailVo.setCover(imgFileSuffix+courseDetailVo.getCover());
       }
        courseDetailVo.setMajors(majors);
        courseDetailVo.setChapters(chaptersVos);
        return ResultT.success(courseDetailVo);
    }

    /**
     * 新增课程
     *
     * @param
     * @return
     */
    @PostMapping("/commit")
    @ApiOperation("新增课程")
    public ResultT commit(@RequestBody CommitCourseVo commitCourseVo) {

        ResultT resultT = courseService.commit(commitCourseVo);
        if (resultT.getCode() == 200) {
            Map<String,Integer> courseId = (Map<String, Integer>) resultT.getData();
            if (commitCourseVo.getMajor() != null) {
                Coursemajor coursemajor = new Coursemajor();
                coursemajor.setCourseId(courseId.get("courseId"));
                coursemajor.setMajorId(commitCourseVo.getMajor());

                coursemajorService.save(coursemajor);
            }


            if (commitCourseVo.getModule() != null) {
                Coursemajor coursemajor = new Coursemajor();
                coursemajor.setCourseId(courseId.get("courseId"));
                coursemajor.setMajorId(commitCourseVo.getModule());

                coursemajorService.save(coursemajor);
            }
        }
        return resultT;
    }


//    @GetMapping("/checkTitleExist")
//    @ApiOperation("检查课程名称是否存在")
//    public ResultT checkTitleExist(@RequestBody CourseTitleVo courseTitleVo) {
//
//        String title = courseTitleVo.getTitle();
//
//        if (StrUtil.isNotEmpty(title)) {
//            List<String> titleList = courseMapper.getTitle();
//            if (CollUtil.contains(titleList, title)) {
//                return ResultT.fail("课程名称重复");
//            } else {
//                return ResultT.success();
//            }
//        } else {
//            return ResultT.success();
//        }
//    }


    @GetMapping("/checkTitleExist")
    @ApiOperation("检查课程名称是否存在")
    public ResultT checkTitleExist(String title) {

//        String title = courseTitleVo.getTitle();

        if (StrUtil.isNotEmpty(title)) {
            List<String> titleList = courseMapper.getTitle();
            if (CollUtil.contains(titleList, title)) {
                return ResultT.fail("课程名称重复");
            } else {
                return ResultT.success();
            }
        } else {
            return ResultT.success();
        }
    }

    @GetMapping("/exportCourseDataDetail")
    public void exportCourseDataDetail(String courseId, String keyword, HttpServletResponse response) throws IOException {

        QueryWrapper<CourseDataDetailVo> qw = new QueryWrapper<>();
        qw.orderByDesc("id");
        if (courseId != null) {
            qw.eq("`userjoinedcourse`.`courseId`", courseId);
        }
        if (StrUtil.isNotEmpty(keyword)) {
            qw.like("`user`.`realname`", keyword);
        }
        ArrayList<Map<String, Object>> exportExamineeVos = new ArrayList<>();
        List<CourseDataDetailVo> courseDataDetailVoList = courseMapper.detail(qw);
        for (CourseDataDetailVo courseDataDetailVo : courseDataDetailVoList) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();


            map.put("真实姓名", courseDataDetailVo.getName());
            map.put("性别", courseDataDetailVo.getGender());
            map.put("用户名", courseDataDetailVo.getAccount());
            map.put("账号", courseDataDetailVo.getAccount());
            map.put("手机号", courseDataDetailVo.getTelephone());
            map.put("身份证号", courseDataDetailVo.getIdCardNum());
            map.put("所属单位", courseDataDetailVo.getInstituteName());
            map.put("所属班级", courseDataDetailVo.getPaperRecord());
            map.put("班级教师", courseDataDetailVo.getTaskProgress());
            map.put("学习进度", courseDataDetailVo.getPaperRecord());
            map.put("成绩", courseDataDetailVo.getTaskProgress());
            map.put("是否合格", "");
            map.put("考试时间", "");
            map.put("证书编号", "");
            exportExamineeVos.add(map);
        }

        if (CollUtil.isNotEmpty(exportExamineeVos)) {

            ExcelWriter writer = ExcelUtil.getWriter();
            writer.write(exportExamineeVos, true);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = URLEncoder.encode("考生列表", "UTF-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out);
            writer.close();

        }
    }
}
